package com.cch.cooperation.api.support.util;

import cn.hutool.crypto.digest.MD5;

import java.util.Random;

/**
 * 密码工具类
 *
 * @author cch
 */
public class PasswordUtil {

    private final static String[] chars = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM".split("");
    private final static String[] specialChars = "?.@!".split("");
    private final static String[] numChars = "1234567890".split("");

    /**
     * 生成密码
     *
     * @param password 原始密码
     * @param salt     盐
     * @return String
     */
    public static String generate(String password, String salt) {
        MD5 md5 = MD5.create();
        return md5.digestHex(password + salt).toUpperCase();
    }

    /**
     * 生成随机密码
     */
    public static String random() {
        Random random = new Random();
        StringBuilder passwordBuilder = new StringBuilder();
        while (passwordBuilder.length() < 8) {
            if (passwordBuilder.length() < 4) {
                passwordBuilder.append(chars[random.nextInt(chars.length)]);
            } else if (passwordBuilder.length() < 7) {
                passwordBuilder.append(numChars[random.nextInt(numChars.length)]);
            } else {
                passwordBuilder.append(specialChars[random.nextInt(specialChars.length)]);
            }
        }
        return passwordBuilder.toString();
    }

    /**
     * 生成随机数字密码
     */
    public static String randomNum(int len) {
        Random random = new Random();
        StringBuilder passwordBuilder = new StringBuilder();
        while (passwordBuilder.length() < len) {
            passwordBuilder.append(numChars[random.nextInt(numChars.length)]);
        }
        return passwordBuilder.toString();
    }

}
